package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"yukao1/models/mysql"
	"yukao1/models/redis"
	"yukao1/models/request"
)

func CreateOrder(c *gin.Context) {
	var data request.OrderRequest
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	order := mysql.CreateOrder(data)
	if order.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,

			"msg": "新增订单失败",
		})
		return
	}
	//转json
	marshal, err := json.Marshal(order)
	if err != nil {
		zap.S().Error("转json失败", err)
		return
	}
	//储存到缓存中
	redis.RedisSetOrderData(data.UserId, string(marshal))
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "新增订单成功",
	})

}

// 订单查询  根据用户id查询
func GetUserIdOrder(c *gin.Context) {
	var data request.OrderRequest
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var order []mysql.OrderYk
	//先从缓存中获取数据
	orderData := redis.RedisGetOrderData(data.UserId)
	if orderData != "" {
		var o mysql.OrderYk
		fmt.Println("缓存有数据展示缓存的数据")
		json.Unmarshal([]byte(orderData), &o)
		order = append(order, o)
		fmt.Println(o)
	} else {
		fmt.Println("缓存没有数据mysql查询数据")
		order = mysql.GetUserIdOrder(data)
		if len(order) == 0 {
			c.JSON(http.StatusBadRequest, gin.H{
				"code": http.StatusBadRequest,
				"msg":  "未查询到订单数据",
			})
			return
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "获取订单数据成功",
		"data": order,
	})

}

// 根据商品查询订单详情
func GetOrderByGoodsName(c *gin.Context) {
	var data request.KeywordOrdersList
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	list := mysql.GetOrderByGoodsName(data)
	if len(list) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "未查询到订单数据",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "查询成功",
		"data": list,
	})

}
